package com.xdf.xzymanagementsystem.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author chanchaw
 * @create 2022-08-19 10:52
 * 自定义线程池，用于做辅助任务
 */
@Component
public class CcThreadPool {

    @Value("${globalv.threadcount}")
    private int threadCount;
    static ExecutorService threadPool;
    static {
        Runtime.getRuntime().addShutdownHook(new Thread(() -> shutdown(threadPool)));
    }

    //@PreDestroy - 销毁时调用
    @PostConstruct
    public void init(){
        threadPool = Executors.newFixedThreadPool(threadCount, new ThreadFactory() {
            private AtomicInteger i = new AtomicInteger(1);

            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r,"ccThreadPool" + i.getAndIncrement());
            }
        });
    }

    public void execute(Runnable task){
        task.run();
    }

    // 关闭线程池的钩子函数
    private static void shutdown(ExecutorService executorService) {
        // 第一步：使新任务无法提交
        executorService.shutdown();
        try {
            // 第二步：等待未完成任务结束
            if(!executorService.awaitTermination(60, TimeUnit.SECONDS)) {
                // 第三步：取消当前执行的任务
                executorService.shutdownNow();
                // 第四步：等待任务取消的响应
                if(!executorService.awaitTermination(60, TimeUnit.SECONDS)) {
                    System.err.println("Thread pool did not terminate");
                }
            }
        } catch(InterruptedException ie) {
            // 第五步：出现异常后，重新取消当前执行的任务
            executorService.shutdownNow();
            Thread.currentThread().interrupt(); // 设置本线程中断状态
        }
    }
}
